<?php
/**
 * create by breeze
 * Author: breeze
 * Date: 2021/3/27
 */
declare(strict_types=1);
namespace app\common\lib\sms;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
class AliSms
{
    public static function sendCode(string $phone, int $code) :bool {
        if(empty($phone) || empty($code)){
            return false;
        }
        $path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
        if (file_exists($path)) {
            require_once $path;
        }
        $argv = [
            "phone" => $phone,
            "code" => $code
        ];
        AliSms::main(array_slice($argv, 0));
//        Sample::main(array_slice($argv, 1));
        return true;
    }
    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Dysmsapi Client
     */
    public static function createClient($accessKeyId, $accessKeySecret){
        $config = new Config([
            // 您的AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 您的AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
        // 访问的域名
        $config->endpoint = config('aliyun.host');
        return new Dysmsapi($config);
    }

    /**
     * @param string[] $args
     * @return void
     */
    public static function main($args){
        $templateParam = [
            "code" => $args['code']
        ];
        $client = self::createClient(config('aliyun.access_key_id'), config('aliyun.access_key_secret'));
        $sendSmsRequest = new SendSmsRequest([
            "signName" => config('aliyun.signName'),
            "templateCode" => config('aliyun.templateCode'),
            "templateParam" => json_encode($templateParam),
            "phoneNumbers" => $args["phone"]
        ]);
        // 复制代码运行请自行打印 API 的返回值
        $client->sendSms($sendSmsRequest);
    }
}